package org.cms.dao;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.List;
import java.util.logging.Logger;

/**
 * Created by elnoa on 29/10/14.
 */
public abstract class AbstractDao<E,K> implements IDao<E,K> {

    Logger log = Logger.getLogger(AbstractDao.class.getName());
    protected Class entityClass;

    @PersistenceContext(unitName = "dbunit")
    protected EntityManager em;

    public AbstractDao() {
        ParameterizedType genericSuperclass = (ParameterizedType) getClass().getGenericSuperclass();
        log.info("size of par: "+ genericSuperclass.getActualTypeArguments().length);
        for (Type t : genericSuperclass.getActualTypeArguments()) {
            log.info("Type is " + t.getTypeName());
        }
        this.entityClass = (Class) genericSuperclass.getActualTypeArguments()[0];
        log.info("name of the class " +this.entityClass.getName());
    }


    public <E> void persist(E entity) {
        em.persist(entity);
    }

    public <E> void merge(E entity) {
        em.merge(entity);
    }

    public <E> void remove(E entity) {
        em.remove(entity);
    }

    @Override
    public <E, K> E findById(K primaryKey) {
        E entity = (E) em.find(entityClass, primaryKey);
        if (entity != null) {
            return entity;
        }else{
            return null;
        }
    }

//    public <T> T findById(Class<T> entityClass, Object primaryKey) {
//        T entity = em.find(entityClass, primaryKey);
//        if (entity != null) {
//            return entity;
//        }else{
//            return null;
//        }
//    }

    public <E> void mergeList(List<E> entityList) {
        log.info("persisting the list: "+ entityList.size());
        for (int i = 0; i < entityList.size(); i++) {
            em.merge(entityList.get(i));
            if ( i % 20 == 0 ) {
                log.info("Flushing "+ entityList.size());
                em.flush();
                em.clear();
            }
        }
    }

}


